package com.contact;

import java.io.File;

import com.app.DemoApplication;
import com.easemob.chatuidemo.utils.CommonUtils;
import com.easemob.util.PathUtil;
import com.util.ImageHelper;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

/**
 * 
 * @ClassName:BasePhotoActivity
 * @Description:TODO此类封装了拍照和从相册选取的方法，当拍照或相册后会获取路径，并执行donePhoto，子类拿到路径进行处理
 * @author zhuw
 * @date 2013-8-17 上午8:35:21
 */
public abstract class AbstractPhotoActivity extends BaseActivity  {

	/***
	 * 使用照相机拍照获取图片
	 */
	private static final int SELECT_PIC_BY_TAKE_PHOTO = 11;
	/***
	 * 使用相册中的图片
	 */
	private static final int SELECT_PIC_BY_PICK_PHOTO = 22;


	private Uri photoUri;
	/******此三字段用于解决在机构简介界面，会传2个证件图片START*****************/
	protected static String FLAG_MAIN_PERMIT="FLAG_MAIN_PERMIT";//主证件图片
	protected static String FLAG_OTHER_PERMIT="FLAG_OTHER_PERMIT";//其他证件图片
	protected String tabFlag=null;
	/******此三字段用于解决在机构简介界面，会传2个证件图片END*****************/

	/**
	 * 
	 * @Description:TODO当拍照或相册获取到路径后子类回调
	 * @param@param photoPath
	 * @return void
	 * @author zhuw
	 * @date 2013-8-17 下午1:12:25
	 */
	protected abstract void donePhoto(String photoPath);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}



	private File cameraFile;

	/**
	 * 拍照获取图片
	 */
	protected void takePhoto() {
		//		// 执行拍照前，应该先判断SD卡是否存在
		//		String SDState = Environment.getExternalStorageState();
		//		if (SDState.equals(Environment.MEDIA_MOUNTED)) {
		//
		//			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// "android.media.action.IMAGE_CAPTURE"
		//			/***
		//			 * 需要说明一下，以下操作使用照相机拍照，拍照后的图片会存放在相册中的 这里使用的这种方式有一个好处就是获取的图片是拍照后的原图
		//			 * 如果不实用ContentValues存放照片路径的话，拍照后获取的图片为缩略图不清晰
		//			 */
		//			ContentValues values = new ContentValues();
		//			photoUri = this.getContentResolver().insert(
		//					MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
		//			intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, photoUri);
		//			/** ----------------- */
		//			startActivityForResult(intent, SELECT_PIC_BY_TAKE_PHOTO);
		//		} else {
		//			Toast.makeText(this, "内存卡不存在", Toast.LENGTH_LONG).show();
		//		}

		if (!CommonUtils.isExitsSdcard()) {
			Toast.makeText(getApplicationContext(), "SD卡不存在，不能拍照", 0).show();
			return;
		}

		cameraFile = new File(PathUtil.getInstance().getImagePath(), DemoApplication.getInstance().getUserName()
				+ System.currentTimeMillis() + ".jpg");
		cameraFile.getParentFile().mkdirs();
		startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)),
				SELECT_PIC_BY_TAKE_PHOTO);
	}

	/***
	 * 从相册中取图片
	 */
	protected void pickPhoto() {
		Intent intent = new Intent();
		intent.setType("image/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);
		startActivityForResult(intent, SELECT_PIC_BY_PICK_PHOTO);
	}

	private String localTempImgDir = Environment
			.getExternalStorageDirectory() + "/mytup";
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK && requestCode == SELECT_PIC_BY_TAKE_PHOTO) {
			if (cameraFile != null && cameraFile.exists()){
				String testPath = cameraFile.getAbsolutePath();
				Log.i("test", "发送图片的路径=="+testPath);
				
				Bitmap ysBitmap;
				Bitmap bitmap;
				File file = new File(localTempImgDir);
				if (!file.exists()) {
					file.mkdirs();
				}
				ysBitmap = ImageHelper.createNewBitmapAndCompressByFile(
						testPath, new int[] { 640, 480 });
				bitmap = ImageHelper.comp(ysBitmap);
				File newfile = new File(localTempImgDir + "/"
						+ System.currentTimeMillis() + ".jpg");
				boolean sucess = ImageHelper.saveCompressBitmap(bitmap,
						newfile);


				//	File newFile = new File(testPath);
				if (sucess) {
					String name = newfile.getName();
					String ss = newfile.getAbsolutePath();
					//String path =ss.substring(0,ss.lastIndexOf("/"))+"/";
					donePhoto(ss);
				}
				
				
			

			}else {
				Toast.makeText(getApplicationContext(), "获取图片失败，建议从相册选择", 1).show();
			}

		}else {
			doPhoto(requestCode, data);
		}

	}

	/**
	 * 选择图片后，获取图片的路径
	 * 
	 * @param requestCode
	 * @param data
	 */
	private void doPhoto(int requestCode, Intent data) {
		if (requestCode == SELECT_PIC_BY_PICK_PHOTO) // 从相册取图片，有些手机有异常情况，请注意
		{
			if (data == null) {
				Toast.makeText(this, "选择图片文件出错", Toast.LENGTH_LONG).show();
				return;
			}
			photoUri = data.getData();
			if (photoUri == null) {
				Toast.makeText(this, "选择图片文件出错", Toast.LENGTH_LONG).show();
				return;
			}
		}
		String[] pojo = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(photoUri, pojo, null, null, null);
		String picPath=null;
		if (cursor != null) {
			int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
			cursor.moveToFirst();
			picPath = cursor.getString(columnIndex);
			try  
			{  
				//4.0以上的版本会自动关闭 (4.0--14;; 4.0.3--15)  
				if(Integer.parseInt(Build.VERSION.SDK) < 14)  
				{  
					cursor.close();  
				}  
			}catch(Exception e)  
			{  
				Log.e(TAG, "error:" + e);  
			}  
		}
		Log.i(TAG, "imagePath = " + picPath);
		if (picPath != null
				&& (picPath.endsWith(".png") || picPath.endsWith(".PNG")
						|| picPath.endsWith(".jpg") || picPath.endsWith(".JPG"))) {
			
			Bitmap ysBitmap;
			Bitmap bitmap;
			File file = new File(localTempImgDir);
			if (!file.exists()) {
				file.mkdirs();
			}
			ysBitmap = ImageHelper.createNewBitmapAndCompressByFile(
					picPath, new int[] { 640, 480 });
			bitmap = ImageHelper.comp(ysBitmap);
			File newfile = new File(localTempImgDir + "/"
					+ System.currentTimeMillis() + ".jpg");
			boolean sucess = ImageHelper.saveCompressBitmap(bitmap,
					newfile);


			//	File newFile = new File(testPath);
			if (sucess) {
				String name = newfile.getName();
				String ss = newfile.getAbsolutePath();
				//String path =ss.substring(0,ss.lastIndexOf("/"))+"/";
				donePhoto(ss);
			}
			
		//	donePhoto(picPath);
		} else {
			Toast.makeText(this, "选择图片文件不正确", Toast.LENGTH_LONG).show();
		}
	}
}
